package com.nbcio.modules.erp.goods.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nbcio.modules.erp.cache.dto.CombinedData;
import com.nbcio.modules.erp.cache.service.CacheService;
import com.nbcio.modules.erp.cache.service.ErpDataService;
import com.nbcio.modules.erp.cache.service.MaterialimagBService;
import com.nbcio.modules.erp.goods.entity.ErpGoods;
import com.nbcio.modules.erp.goods.entity.ErpGoodsCategory;
import com.nbcio.modules.erp.goods.entity.ErpGoodsPrice;
import com.nbcio.modules.erp.goods.mapper.ErpGoodsMapper;
import com.nbcio.modules.erp.goods.mapper.ErpGoodsPriceMapper;
import com.nbcio.modules.erp.goods.service.IErpGoodsCategoryService;
import com.nbcio.modules.erp.goods.service.IErpGoodsPriceService;
import com.nbcio.modules.erp.goods.service.IErpGoodsService;
import com.nbcio.modules.erp.stock.entity.ErpGoodsStock;
import com.nbcio.modules.erp.stock.service.IErpGoodsStockService;
import com.nbcio.modules.estar.customerpriceh.service.ICustomerpriceHService;
import com.nbcio.modules.estar.materialimag.entity.Materialimag;
import com.nbcio.modules.estar.materialimag.entity.MaterialimagB;
import com.nbcio.modules.estar.materialimag.service.IMaterialimagBService;
import com.nbcio.modules.estar.materialimag.service.IMaterialimagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 商品基础信息
 * @Author: nbacheng
 * @Date: 2023-03-08
 * @Version: V1.0
 */
@Service
public class ErpGoodsServiceImpl extends ServiceImpl<ErpGoodsMapper, ErpGoods> implements IErpGoodsService {

    @Autowired
    private ErpGoodsMapper erpGoodsMapper;
    @Autowired
    private ErpGoodsPriceMapper erpGoodsPriceMapper;

    @Autowired
    private IErpGoodsPriceService erpGoodsPriceService;

    @Autowired
    private IErpGoodsStockService erpGoodsStockService;

    @Autowired
    private IMaterialimagService materialimagService;

    @Autowired
    private IMaterialimagBService materialimagBService;

    @Autowired
    private IErpGoodsCategoryService erpGoodsCategoryService;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ErpDataService erpDataService;

    @Autowired
    private MaterialimagBService materialbService;

    @Autowired
    ICustomerpriceHService customerpriceService;
    private Executor executor = Executors.newCachedThreadPool();

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional
    public void saveMain(ErpGoods erpGoods, List<ErpGoodsPrice> erpGoodsPriceList) {
        erpGoodsMapper.insert(erpGoods);
        if (erpGoodsPriceList != null && erpGoodsPriceList.size() > 0) {
            for (ErpGoodsPrice entity : erpGoodsPriceList) {
                //外键设置
                entity.setId(erpGoods.getId());
                erpGoodsPriceMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void updateMain(ErpGoods erpGoods, List<ErpGoodsPrice> erpGoodsPriceList) {
        erpGoodsMapper.updateById(erpGoods);

        //1.先删除子表数据
        erpGoodsPriceMapper.deleteByMainId(erpGoods.getId());

        //2.子表数据重新插入
        if (erpGoodsPriceList != null && erpGoodsPriceList.size() > 0) {
            for (ErpGoodsPrice entity : erpGoodsPriceList) {
                //外键设置
                entity.setId(erpGoods.getId());
                erpGoodsPriceMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional
    public void delMain(String id) {
        erpGoodsPriceMapper.deleteByMainId(id);
        erpGoodsMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            erpGoodsPriceMapper.deleteByMainId(id.toString());
            erpGoodsMapper.deleteById(id);
        }
    }

    @Override
    public void listing(String id) {
        UpdateWrapper<ErpGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("listing_status", "1");
        erpGoodsMapper.update(updateWrapper);
    }

    @Override
    public void deListing(String id) {
        UpdateWrapper<ErpGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("listing_status", "0");
        erpGoodsMapper.update(updateWrapper);
    }


    @Override
    public Map<String, Object> detail(String id) {
        Map<String, Object> map = new HashMap<>();
        ErpGoods erpGoods = getById(id);
        List<ErpGoodsPrice> erpGoodsPriceList = erpGoodsPriceService.selectByMainId(id);
        List<ErpGoodsStock> erpGoodsStockList = erpGoodsStockService.list(new LambdaQueryWrapper<ErpGoodsStock>()
                .eq(ErpGoodsStock::getGoodsId, id));

        long count = Optional.ofNullable(erpGoodsStockList)
                .map(list -> list.stream().mapToInt(ErpGoodsStock::getStockNum).sum())
                .orElse(0);

        Map<String, Object> imgMap = new HashMap<>();
        Materialimag materialimag = materialimagService.getOne(new LambdaQueryWrapper<Materialimag>()
                .eq(Materialimag::getMaterial, id)
                .eq(Materialimag::getDes, "1"));

        imgMap.put("big", Optional.ofNullable(materialimag).map(Materialimag::getImg).orElse(""));
        imgMap.put("small", new ArrayList<>()); // 直接初始化为空列表

        Optional.ofNullable(materialimag)
                .ifPresent(m -> {
                    LambdaQueryWrapper<MaterialimagB> materialimagBLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    materialimagBLambdaQueryWrapper.eq(MaterialimagB::getIdH, m.getId())
                            .eq(MaterialimagB::getIsxs, "1");
                    List<MaterialimagB> materialimagBList = materialimagBService.list(materialimagBLambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(materialimagBList)) {
                        List<String> smallImgList = materialimagBList.stream()
                                .sorted(Comparator.comparingInt(p -> {
                                    String num = "1";
                                    if (p.getNum() != null && !p.getNum().isEmpty()) {
                                        num = p.getNum();
                                    }
                                    return Integer.parseInt(num);
                                }))
                                .map(MaterialimagB::getImg)
                                .collect(Collectors.toList());
                        imgMap.put("small", smallImgList);
                    }
                });


        BigDecimal sale = customerpriceService.getPrice(null, erpGoods.getCategoryId(), erpGoods.getId(), erpGoodsPriceList.get(0).getSale());
        if (sale != null) {
            erpGoodsPriceList.get(0).setSale(sale);
        }
        map.put("main", erpGoods);
        map.put("sub", erpGoodsPriceList);
        map.put("img", Collections.singletonList(imgMap));
        map.put("stock_num", count);
        map.put("info", materialimag.getLnformation());

        return map;
    }

    /**
     * 详情查询异步处理
     *
     * @param id
     * @return
     */
    public CompletableFuture<Map<String, Object>> fetchOptimizedDataAsync(String id) {
        // 初始化结果容器
        ConcurrentHashMap<String, Object> resultMap = new ConcurrentHashMap<>();

        // 异步获取ErpGoods信息，使用缓存策略
        CompletableFuture<ErpGoods> erpGoodsFuture = CompletableFuture.supplyAsync(() -> {
            ErpGoods erpGoods = new ErpGoods();
            try {
                erpGoods = cacheService.getCachedErpGoods(id);
                if (erpGoods == null) {
                    erpGoods = getById(id);
                    cacheService.cacheErpGoods(erpGoods);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            return erpGoods;
        });


        // 合并查询ErpGoodsPrice和ErpGoodsStock，以及Materialimag和MaterialimagB的异步任务
        CompletableFuture<List<CombinedData>> combinedDataFuture = CompletableFuture.supplyAsync(() ->
                erpDataService.getCombinedDataById(id)
        );

        // 计算总库存的异步任务
        CompletableFuture<Long> stockCountFuture = combinedDataFuture.thenCompose(combinedDataList -> {
            if (!combinedDataList.isEmpty()) {
                return CompletableFuture.completedFuture(
                        combinedDataList.stream().mapToLong(CombinedData::getTotalStockNum).sum()
                );
            } else {
                return CompletableFuture.completedFuture(0L);
            }
        });

        // 获取并处理图片信息的异步任务
        CompletableFuture<Map<String, Object>> imgInfoFuture = combinedDataFuture.thenCompose(combinedDataList -> {
            Map<String, Object> map = new HashMap<>();
            if (!combinedDataList.isEmpty()) {
                CombinedData mainData = combinedDataList.get(0);
                Materialimag materialimag = mainData.getMaterialimag();
                map.put("big", materialimag != null ? materialimag.getImg() : "");
                map.put("small", materialimag != null
                        ? materialbService.getSortedSmallImages(materialimag.getId(), "1")
                        : Collections.emptyList());
                return CompletableFuture.completedFuture(map);
            } else {
                map.put("big", "");
                map.put("small", Collections.emptyList());
                return CompletableFuture.completedFuture(map);
            }
        });

        // 设置价格的异步任务
        CompletableFuture<Void> setPriceFuture = combinedDataFuture.thenAcceptAsync(combinedDataList -> {
            if (!combinedDataList.isEmpty()) {
                List<ErpGoodsPrice> subList = combinedDataList.get(0).getErpGoodsPrices();
                BigDecimal salePrice = customerpriceService.getPrice(null, combinedDataList.get(0).getErpGoods().getCategoryId(), id, subList.get(0).getSale());
                if (salePrice != null) {
                    subList.get(0).setSale(salePrice);
                }
            }
        });

        // 组合所有异步结果
        return CompletableFuture.allOf(erpGoodsFuture, combinedDataFuture, stockCountFuture, imgInfoFuture, setPriceFuture)
                .thenApplyAsync(v -> {
                    ErpGoods erpGoods = erpGoodsFuture.join();
                    List<ErpGoodsPrice> subList = combinedDataFuture.join().get(0).getErpGoodsPrices();
                    Long count = stockCountFuture.join();
                    Map<String, Object> imgMap = imgInfoFuture.join();

                    resultMap.put("main", erpGoods);
                    resultMap.put("sub", subList);
                    resultMap.put("img", Collections.singletonList(imgMap));
                    resultMap.put("stock_num", count);
                    // 注意：此处假设materialimag信息直接从combinedData获取，或需调整
                    resultMap.put("info", combinedDataFuture.join().get(0).getMaterialimag().getLnformation());

                    return resultMap;
                });
    }


    /**
     * 根据分类获取商品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Map<String, Object>> detailByCategoryId(String categoryId, int page, int size) {
        List<ErpGoods> erpGoodsList;
        Page<ErpGoods> pageVO = new Page<>(page, size);
        if ("-1".equals(categoryId)) {
            erpGoodsList = page(pageVO).getRecords();
        } else {
            LambdaQueryWrapper<ErpGoods> goodsWrapper = new LambdaQueryWrapper<>();
            goodsWrapper.eq(ErpGoods::getCategoryId, categoryId);
            erpGoodsList = page(pageVO, goodsWrapper).getRecords();
        }

        if (CollectionUtil.isEmpty(erpGoodsList)) {

            // 当前分类无商品，查询所有上级分类的商品
            List<ErpGoodsCategory> erpGoodsCategoryList = getSuperiorCategories(categoryId);
            if (!CollectionUtil.isEmpty(erpGoodsCategoryList)) {
                List<String> categoryIds = erpGoodsCategoryList.stream()
                        .map(ErpGoodsCategory::getId)
                        .collect(Collectors.toList());

                LambdaQueryWrapper<ErpGoods> goodsWrapper = new LambdaQueryWrapper<>();
                goodsWrapper.in(ErpGoods::getCategoryId, categoryIds);

                erpGoodsList = page(pageVO, goodsWrapper).getRecords();
            }
        }

        return buildErpGoodsDataMap(erpGoodsList);
    }


    /**
     * 分类查询异步处理
     *
     * @param page
     * @param size
     * @param categoryId
     * @return
     */
    @Override
    public CompletableFuture<List<Map<String, Object>>> fetchErpGoodsDataAsync(String categoryId, int page, int size) {

        Page<ErpGoods> pageVO = new Page<>(page, size);

        CompletableFuture<List<ErpGoods>> erpGoodsFuture;
        if ("-1".equals(categoryId)) {
            erpGoodsFuture = CompletableFuture.supplyAsync(() -> page(pageVO).getRecords());
        } else {
            CompletableFuture<LambdaQueryWrapper<ErpGoods>> wrapperFuture = CompletableFuture.completedFuture(
                    new LambdaQueryWrapper<ErpGoods>().eq(ErpGoods::getCategoryId, categoryId)
            );
            erpGoodsFuture = wrapperFuture.thenComposeAsync(wrapper ->
                    CompletableFuture.supplyAsync(() -> page(pageVO, wrapper).getRecords())
            );
        }

        CompletableFuture<List<ErpGoodsCategory>> superiorsFuture = erpGoodsFuture.thenComposeAsync(erpGoodsList -> {
            if (CollectionUtil.isEmpty(erpGoodsList)) {
                return CompletableFuture.supplyAsync(() -> getSuperiorCategories(categoryId));
            } else {
                return CompletableFuture.completedFuture(Collections.emptyList());
            }
        });

        CompletableFuture<List<String>> categoryIdsFuture = superiorsFuture.thenApplyAsync(categories ->
                categories.stream().map(ErpGoodsCategory::getId).collect(Collectors.toList())
        );

        CompletableFuture<List<ErpGoods>> fallbackGoodsFuture = categoryIdsFuture.thenComposeAsync(ids -> {
            if (!ids.isEmpty()) {
                LambdaQueryWrapper<ErpGoods> goodsWrapper = new LambdaQueryWrapper<>();
                goodsWrapper.in(ErpGoods::getCategoryId, ids);
                return CompletableFuture.supplyAsync(() -> page(pageVO, goodsWrapper).getRecords());
            } else {
                return CompletableFuture.completedFuture(Collections.emptyList());
            }
        });

        // 组合所有结果
        return CompletableFuture.allOf(erpGoodsFuture, fallbackGoodsFuture)
                .thenApplyAsync(unused -> {
                    List<ErpGoods> allGoods = Stream.concat(
                            erpGoodsFuture.join().stream(),
                            fallbackGoodsFuture.join().stream()
                    ).collect(Collectors.toList());

//                    return allGoods.stream()
//                            .map(erpGoods -> {
//                                try {
//                                    return handleAsync(erpGoods).get();
//                                } catch (Exception e) {
//                                    throw new RuntimeException(e);
//                                }
//                            })
//                            .collect(Collectors.toList());
                    return allGoods.stream().map(erpGoods -> {
                        try {
                            return fetchOptimizedDataAsync(erpGoods.getId()).get();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        } catch (ExecutionException e) {
                            throw new RuntimeException(e);
                        }
                    }).collect(Collectors.toList());
                });
    }

    /**
     * 根据名称模糊查询
     *
     * @param name
     * @return
     */
    @Override
    public List<Map<String, Object>> queryGoodsByName(String name) {

        if (StringUtils.isNotBlank(name)) {

            LambdaQueryWrapper<ErpGoods> goodsWrapper = new LambdaQueryWrapper<>();
            goodsWrapper.like(ErpGoods::getName, name);
            List<ErpGoods> erpGoodsList = list(goodsWrapper);
//            for (ErpGoods erpGoods : erpGoodsList) {
//                ErpGoodsPrice erpGoodsPrice = erpGoodsPriceService.getById(erpGoods.getId());
//                erpGoodsPrice.setSale(customerpriceService.getPrice(null, erpGoods.getId(), erpGoods.getCategoryId(), erpGoodsPrice.getSale()));
//            }

            return buildErpGoodsDataMap(erpGoodsList);
        }
        return new ArrayList<>();
    }


    /**
     * 模糊查询异步处理
     *
     * @param name
     * @return
     */
    @Override
    public List<Map<String, Object>> fetchErpGoodsDataAsync(String name) {
        if (StringUtils.isNotBlank(name)) {
            // 异步获取商品列表
            CompletableFuture<List<ErpGoods>> goodsFuture = CompletableFuture.supplyAsync(() -> {
                LambdaQueryWrapper<ErpGoods> goodsWrapper = new LambdaQueryWrapper<>();
                goodsWrapper.like(ErpGoods::getName, name);
                return list(goodsWrapper);
            });

            // 异步处理每个商品的价格更新，并收集结果
            CompletableFuture<List<Map<String, Object>>> resultFuture = goodsFuture.thenApplyAsync(erpGoodsList -> {
                List<CompletableFuture<Void>> priceUpdateFutures = new ArrayList<>();
                for (ErpGoods erpGoods : erpGoodsList) {
                    CompletableFuture<Void> priceUpdateFuture = CompletableFuture.runAsync(() -> {
                        ErpGoodsPrice erpGoodsPrice = erpGoodsPriceService.getById(erpGoods.getId());
                        if (erpGoodsPrice != null) {
                            BigDecimal updatedSale = customerpriceService.getPrice(null, erpGoods.getId(), erpGoods.getCategoryId(), erpGoodsPrice.getSale());
                            erpGoodsPrice.setSale(updatedSale);
                        }
                    });
                    priceUpdateFutures.add(priceUpdateFuture);
                }

                // 等待所有价格更新完成
                CompletableFuture.allOf(priceUpdateFutures.toArray(new CompletableFuture[0])).join();

                // 构建数据映射
//                return erpGoodsList.stream()
//                        .map(erpGoods -> {
//                            try {
//                                return handleAsync(erpGoods).get();
//                            } catch (Exception e) {
//                                throw new RuntimeException(e);
//                            }
//                        })
//                        .collect(Collectors.toList()).stream().filter(map->!map.isEmpty()).collect(Collectors.toList());
                return erpGoodsList.stream().map(erpGoods -> {
                    try {
                        return fetchOptimizedDataAsync(erpGoods.getId()).get();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } catch (ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());
            });

            try {
                return resultFuture.get();
            } catch (Exception e) {
                // 异常处理逻辑
                e.printStackTrace();
                return new ArrayList<>();
            }
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 根据分类获取下级分类
     *
     * @param categoryId
     * @return
     */
    private List<ErpGoodsCategory> getSuperiorCategories(String categoryId) {
        LambdaQueryWrapper<ErpGoodsCategory> categoryWrapper = new LambdaQueryWrapper<>();
        categoryWrapper.eq(ErpGoodsCategory::getParentId, categoryId);
        return erpGoodsCategoryService.list(categoryWrapper);
    }

    /**
     * 构建返回值
     *
     * @param erpGoodsList
     * @return
     */
    private List<Map<String, Object>> buildErpGoodsDataMap(List<ErpGoods> erpGoodsList) {
        return erpGoodsList.stream()
                .map(this::buildErpGoodsDataMapEntry)
                .collect(Collectors.toList());
    }

    /**
     * 构建单个返回值
     *
     * @param erpGoods
     * @return
     */
    private Map<String, Object> buildErpGoodsDataMapEntry(ErpGoods erpGoods) {
        Object object = redisTemplate.opsForValue().get("erp_map:" + erpGoods.getId());
        if (object!=null){
            Map map = JSON.parseObject(JSON.toJSONString(object), Map.class);
            return map;
        }else {

            Map<String, Object> map = new HashMap<>();
            List<Map<String, Object>> imgList = new ArrayList<>();
            Map<String, Object> imgMap = new HashMap<>();

            List<ErpGoodsPrice> erpGoodsPriceList = erpGoodsPriceService.selectByMainId(erpGoods.getId());
            LambdaQueryWrapper<Materialimag> materialimagLambdaQueryWrapper = new LambdaQueryWrapper<>();
            Materialimag materialimag = materialimagService.getOne(materialimagLambdaQueryWrapper
                    .eq(Materialimag::getMaterial, erpGoods.getId())
                    .eq(Materialimag::getDes, "1"));

            imgMap.put("big", Optional.ofNullable(materialimag).map(Materialimag::getImg).orElse(""));
            imgList.add(imgMap);

            LambdaQueryWrapper<ErpGoodsStock> erpGoodsStockLambdaQueryWrapper = new LambdaQueryWrapper<>();
            List<ErpGoodsStock> erpGoodsStockList = erpGoodsStockService.list(erpGoodsStockLambdaQueryWrapper
                    .eq(ErpGoodsStock::getGoodsId, erpGoods.getId()));

            long stockCount = Optional.ofNullable(erpGoodsStockList)
                    .map(list -> list.stream().mapToInt(ErpGoodsStock::getStockNum).sum())
                    .orElse(0);
            if (erpGoodsPriceList != null && erpGoodsPriceList.size() > 0) {
                BigDecimal sale = customerpriceService.getPrice(null, erpGoods.getCategoryId(), erpGoods.getId(), erpGoodsPriceList.get(0).getSale());
                if (sale != null) {
                    erpGoodsPriceList.get(0).setSale(sale);
                }
            }

            map.put("main", erpGoods);
            map.put("sub", erpGoodsPriceList);
            map.put("img", imgList);
            map.put("stock_num", stockCount);
            map.put("info", materialimag.getLnformation());

            redisTemplate.opsForValue().set("erp_map:"+erpGoods.getId(), map, 6, TimeUnit.HOURS);
            return map;
        }
    }

    /**
     * 异步构建单个返回值
     *
     * @param erpGoods
     * @return
     */
    public CompletableFuture<Map<String, Object>> handleAsync(ErpGoods erpGoods) throws Exception {

        AtomicInteger stockCount = new AtomicInteger(0);

        return CompletableFuture.supplyAsync(() -> {
            Map<String, Object> map = new HashMap<>();
            List<Map<String, Object>> imgList = new ArrayList<>();
            Map<String, Object> imgMap = new HashMap<>();

            CompletableFuture<List<ErpGoodsPrice>> priceFuture = CompletableFuture.supplyAsync(() -> erpGoodsPriceService.selectByMainId(erpGoods.getId()));
            CompletableFuture<Materialimag> materialimagFuture = CompletableFuture.supplyAsync(() -> materialimagService.getOne(new LambdaQueryWrapper<Materialimag>()
                    .eq(Materialimag::getMaterial, erpGoods.getId())
                    .eq(Materialimag::getDes, "1")));
            CompletableFuture<List<ErpGoodsStock>> stockFuture = CompletableFuture.supplyAsync(() -> erpGoodsStockService.list(new LambdaQueryWrapper<ErpGoodsStock>()
                    .eq(ErpGoodsStock::getGoodsId, erpGoods.getId())));

            CompletableFuture.allOf(priceFuture, materialimagFuture, stockFuture)
                    .thenCompose(v -> {
                        List<ErpGoodsPrice> erpGoodsPriceList = priceFuture.join();
                        Materialimag materialimag = materialimagFuture.join();
                        List<ErpGoodsStock> erpGoodsStockList = stockFuture.join();

                        imgMap.put("big", Optional.ofNullable(materialimag).map(Materialimag::getImg).orElse(""));
                        imgList.add(imgMap);

                        stockCount.addAndGet(Optional.ofNullable(erpGoodsStockList)
                                .map(List::stream)
                                .orElse(Stream.empty())
                                .mapToInt(ErpGoodsStock::getStockNum)
                                .sum());

                        if (!erpGoodsPriceList.isEmpty()) {
                            CompletableFuture<Void> updateSaleFuture = CompletableFuture.runAsync(() -> {
                                BigDecimal sale = customerpriceService.getPrice(null, erpGoods.getCategoryId(), erpGoods.getId(), erpGoodsPriceList.get(0).getSale());
                                if (sale != null) {
                                    erpGoodsPriceList.get(0).setSale(sale);
                                }
                            }, executor);
                        }

                        map.put("main", erpGoods);
                        map.put("sub", erpGoodsPriceList);
                        map.put("img", imgList);
                        map.put("stock_num", stockCount.get());
                        map.put("info", Optional.ofNullable(materialimag).map(Materialimag::getLnformation).orElse(null));

                        return CompletableFuture.completedFuture(map);
                    });
            return map;
        });

    }


}
